<?php 
class Company extends CI_Model {
	public function addCompany($name) {
		$data = array('name' => $name);
		
		$this->db->insert('company', $data);
		
		return $this->db->insert_id();
	}
	
	public function editCompany($cid, $name) {
		$data = array('name' => $name);
		
		$this->db->where('id', $cid);
		$this->db->update('company', $data);
	}
	
	/*public function addUser($cid, $uid) {
		$data = array('cid' => $cid, 'uid' => $uid);
		
		$this->db->insert('company_users', $data);
	}
	
	public function deleteUser($cid, $uid) {
		$data = array('cid' => $cid, 'uid' => $uid);
		
		$this->db->delete('company_users', $data);
	}*/
	public function addUser($cid, $uid) {
		$data = array('cid' => $cid);
		
		$this->db->where('uid', $uid);
		$this->db->update('users', $data);
	}
	
	public function deleteUser($uid) {
		$data = array('cid' => 0);
		
		$this->db->where('uid', $uid);
		$this->db->update('users', $data);
	}
	
	public function getCompany($cid) {
		$company = $this->db->get_where('company', array('id' => $cid));
		$this->db->where('company', $cid);
		$users = $this->db->get('users');
		$users = $users->result();
		$company = $company->row();
		$company->{"users"} = $users;
		
		return $company;
	}
	
	public function getDue($cid) {
		$this->load->model('Jobs');
		
		$users = $this->db->get_where('users', array('company' => $cid));
		$users = $users->result();
		$total = 0;
		
		foreach ($users as $uinfo) {
			$total += $this->Jobs->getDuePrice($uinfo->uid);
			$total += $this->Jobs->getOverduePrice($uinfo->uid);
		}
		
		return $total;
	}
	
	public function getAll() {
		$companies = $this->db->get('company');
		$companies = $companies->result();
		
		for ($i = 0; $i < count($companies); $i++) {
			$this->db->where('company', $companies[$i]->id);
			$users = $this->db->get('users');
			$users = $users->result();
			$companies[$i]->{"users"} = $users;
		}
		
		return $companies;
	}
	
	public function search($str) {
		$this->db->like('name', $str);
		$companies = $this->db->get('company');
		$companies = $companies->result();
		
		for ($i = 0; $i < count($companies); $i++) {
			$sql = "SELECT COUNT(*) AS `total` FROM `users` WHERE `company` = ".$companies[$i]->id;
			$query = $this->db->query($sql);
			$res = $query->row();
			
			
			$companies[$i]->{"users"} = $res->total;
		}
		
		return $companies;
	}
	
	public function deleteCompany($cid) {
		$data = array('id' => $cid);
		
		$this->db->delete('company', $data);
		
	}
}
?>